package net.vsame.url2sql.helper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.vsame.url2sql.dao.JdbcUtils;
import net.vsame.url2sql.domain.Url2SqlContext;

public class SqlHelper {
	
	public static Object execute(){
		Url2SqlContext context = WebHelper.getContext();
		return execute(context.getUrlConfig().getSql(), context.getParams());
	}
	
	public static Object execute(String sql, Map<String, String[]> map){
		List<String> values = new ArrayList<String>();
		Pattern p = Pattern.compile("\\$\\{(.*?)\\}");
		Matcher m = p.matcher(sql);
		StringBuffer sb = new StringBuffer();
		while(m.find()){
			String key = m.group(1);
			String[] value = map.get(key);
			if(value == null){
				throw new RuntimeException(key + "==null");
			}
			StringBuffer temp = new StringBuffer();
			for(String s: value){
				temp.append("?,");
				values.add(s);
			}
			temp.deleteCharAt(temp.length()-1);
			m.appendReplacement(sb, temp.toString());
		}
		m.appendTail(sb);
		sql = sb.toString();
		
		System.out.println(sql);
		System.out.println(values);
		
		//判断读写，如果是写必定包含(insert|update|delete), 反之则为读
		p = Pattern.compile("insert|update|delete|create|drop", Pattern.CASE_INSENSITIVE); 
		m = p.matcher(sql);
		if(m.find()){
			//System.out.println("写");
			return JdbcUtils.execute(sql, values.toArray());
		}else{
			//System.out.println("读");
			return JdbcUtils.queryList(sql, values.toArray());
		}
	}
	
	public static List<String> alltables(){
		return JdbcUtils.getAllTables();
	}
	public static void main(String[] args) {
		Map<String, String[]> map = new HashMap<String, String[]>();
		map.put("a.id", new String[]{"1"});
		map.put("a.name", new String[]{"gaollg"});
		execute("select * from test where id=${a.id} and name like ${a.name}", map);
	}
}
